'''
https://leetcode.cn/problems/minesweeper/description/
minesweeper: 扫雷
'''
from typing import List


class Solution:
    def updateBoard(self, board: List[List[str]], click: List[int]) -> List[List[str]]:
        m , n = len(board), len(board[0])
        directions = [(-1, 0), (1, 0), (0, -1), (0, 1), (-1, -1), (1, 1), (1, -1), (-1, 1)]
        def dfs(i, j):
            n_adjacent_mine = 0
            board[i][j] = 'B'
            for tx, ty in directions:
                tx, ty = tx + i, ty + j
                if 0 <= tx < m and 0 <= ty < n and board[tx][ty] == 'M':
                    n_adjacent_mine += 1
            if n_adjacent_mine:
                board[i][j] = str(n_adjacent_mine)
            else:
                for tx, ty in directions:
                    tx, ty = tx + i, ty + j
                    if 0 <= tx < m and 0 <= ty < n and board[tx][ty] == 'E':
                        dfs(tx, ty)

        r, c = click
        if board[r][c] == 'M':
            board[r][c] = 'X'
            return board
        elif board[r][c] == 'E':
            dfs(r, c)
        return board
